package com.arpa.wms.common.util;

import com.arpa.wms.domain.vo.TreeNodeVO;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * 树形工具类<br/>
 * 将链表转换为属性结构链表<br/>
 * 主要用于前端的 树 展示<br/>
 * https://blog.csdn.net/qq827245563/article/details/78687856
 *
 * @author zhonghang
 *
 */
public class TreeUtils {

	private TreeUtils() {
		throw new IllegalStateException("Utility class");
	}

	public static List<TreeNodeVO> toTreeWithParent(List<TreeNodeVO> list){
		List<TreeNodeVO> treeList = new ArrayList<TreeNodeVO>();
		// 确立第一级
		for (TreeNodeVO tree : list) {
			if ((tree.getLevel().intValue() == 1)) {
				treeList.add(tree);
			}
		}
		for (TreeNodeVO tree : list) {
			toTreeChildren(treeList, tree);
		}
		return treeList;
	}

	public static List<TreeNodeVO> toTree(List<TreeNodeVO> list) {
		List<TreeNodeVO> treeList = new ArrayList<TreeNodeVO>();
		// 确立根节点
		for (TreeNodeVO tree : list) {
			if ("0".equals(tree.getParentCode())) {
				treeList.add(tree);
			}
		}
		for (TreeNodeVO tree : list) {
			toTreeChildren(treeList, tree);
		}
		return treeList;
	}

	/**
	 * 包含全部
	 * @param list
	 * @return
	 */
	public static List<TreeNodeVO> toTreeAll(List<TreeNodeVO> list) {
		List<TreeNodeVO> treeList = new ArrayList<TreeNodeVO>();
		// 确立根节点
		for (TreeNodeVO tree : list) {
			if ("0".equals(tree.getCode())) {
				tree.setSpread(true);
				treeList.add(tree);
			}
		}
		for (TreeNodeVO tree : list) {
			toTreeChildren(treeList, tree);
		}
		return treeList;
	}



	private static void toTreeChildren(List<TreeNodeVO> treeList, TreeNodeVO tree) {
		for (TreeNodeVO node : treeList) {
			if (node.getCode().equals(tree.getParentCode())) {
				if (node.getChildren() == null) {
					node.setChildren(new ArrayList<TreeNodeVO>());
				}
				node.getChildren().add(tree);
			}
			if (node.getChildren() != null) {
				toTreeChildren(node.getChildren(), tree);
			}
		}
	}

}
